package netty.rpc.framework.core.netty.registry;

import lombok.extern.slf4j.Slf4j;
import netty.rpc.framework.core.netty.utils.PropertiesFileUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author guiyiqiao
 * @date 2020/12/10
 */
@Slf4j
public class ZKUtils {
    //节点前缀
    private final static String ZK_REGISTRY_ROOT_PATH = "/netty_rpc";
    //补偿参数
    private static final int BASE_SLEEP_TIME = 1000;

    private static final int MAX_RETRIES = 3;

    //配置文件名
    public final static String propertiesFileName = "netty_rpc.properties";

    //配置文件键
    public final static String zookeeperAddressPropertiesKey = "rpc.zookeeper.address";

    //存储已经注册服务的地址节点
    private static final Map<String, List<String>> SERVICE_ADDRESS_MAP = new ConcurrentHashMap<>();

    private static final Set<String> REGISTERED_PATH_SET = ConcurrentHashMap.newKeySet();

    private static CuratorFramework zkClient;

    //默认zk地址
    private static final String defaultAddress = "127.0.0.1:2181";


    /**
     * 尝试读取配置文件
     * 获取zk的CuratorFramework对象
     *
     * @return
     */
    public static CuratorFramework getZkClient(){
        if(zkClient != null && zkClient.getState() != CuratorFrameworkState.STARTED){
            return zkClient;
        }
        Properties properties = PropertiesFileUtils.readPropertiesFile(propertiesFileName);
        String address = (String) properties.getOrDefault(zookeeperAddressPropertiesKey, defaultAddress);
        ExponentialBackoffRetry exponentialBackoffRetry = new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES);
        zkClient = CuratorFrameworkFactory.newClient(address,exponentialBackoffRetry);
        zkClient.start();
        return zkClient;

    }

    /**
     * 获取某个服务名下的地址节点，若本地已经加载过了会直接尝试在SERVICE_ADDRESS_MAP中获取
     * 若是第一次加载，则将其服务持久节点添加监视器，保证本地地址最新
     * @param zkClient
     * @param serviceName
     * @return
     */
    public static List<String> getChildrenNodes(CuratorFramework zkClient,String serviceName){

        if(SERVICE_ADDRESS_MAP.containsKey(serviceName)){
            return SERVICE_ADDRESS_MAP.get(serviceName);
        }
        String path = ZK_REGISTRY_ROOT_PATH+"/"+serviceName;
        try {
            List<String> nodes = zkClient.getChildren().forPath(path);
            SERVICE_ADDRESS_MAP.put(serviceName,nodes);
            //监视键
            registerWatcher(zkClient,serviceName);
            return nodes;
        } catch (Exception e) {
            log.error("zookeeper获取节点出错！");
        }
        return new ArrayList<>();
    }

    /**
     * 创建一个持久的服务节点，存在则忽略
     * @param zkClient
     * @param serviceName
     */
    public static void createPersistentNode(CuratorFramework zkClient,String serviceName){
        String path = ZK_REGISTRY_ROOT_PATH+"/"+serviceName;
        //检测服务持久节点是否存在
        //try {
        try {
            if(REGISTERED_PATH_SET.contains(serviceName)|| zkClient.checkExists().forPath(path) != null){

            }else {
                zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);

            }
            REGISTERED_PATH_SET.add(serviceName);
       } catch (Exception e) {
            e.printStackTrace();
            log.error("zookeeper创建节点出错！{}",e.getMessage());
        }
    }

    /**
     * 在持久的服务节点挂载一个临时的地址节点
     * @param zkClient
     * @param serviceName
     */
    public static void createEphemeralNode(CuratorFramework zkClient,String serviceName,String serviceUrl){
        String path = ZK_REGISTRY_ROOT_PATH+"/"+serviceName+"/"+serviceUrl;
        try {
            zkClient.create().withMode(CreateMode.EPHEMERAL)
                    .forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("zookeeper创建临时节点失败！");
        }
    }

    /**
     * 监视持久的服务节点下临时地址节点的变化，并随时更新结构到SERVICE_ADDRESS_MAP
     * @param zkClient
     * @param serviceName
     */
    private static void registerWatcher(CuratorFramework zkClient,String serviceName) {
        String path = ZK_REGISTRY_ROOT_PATH+"/"+serviceName;
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, path, true);
        PathChildrenCacheListener pathChildrenCacheListener = (curatorFramework, pathChildrenCacheEvent) -> {
            List<String> serviceAddresses = curatorFramework.getChildren().forPath(path);
            SERVICE_ADDRESS_MAP.put(path, serviceAddresses);
        };
        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        try {
            pathChildrenCache.start();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

        log.info("map = {}",SERVICE_ADDRESS_MAP.toString());
    }
}
